/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
Ext.onReady(function() {
    var area_id;
    var a_store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '../area/all'
        }),
        reader: new Ext.data.JsonReader({
            root: 'areas',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [{
            name: 'id'
        },
        {
            name: 'name_en'
        },
        {
            name: 'name_mk'
        },
        {
            name: 'short'
        },
        {
            name: 'description'
        }])
    });
    var ustore = new Ext.data.Store({
        remoteSort: true,
        sortInfo: {
            field: 'date_sent',
            direction: 'ASC'
        },
        proxy: new Ext.data.HttpProxy({
            url: 'unassigned'
        }),
        reader: new Ext.data.JsonReader({
            root: 'unassigned',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [{
            name: 'id'
        },
        {
            name: 'title'
        },
        {
            name: 'authors'
        },
        {
            name: 'category_name'
        },
        {
            name: 'file_pdf'
        },
        {
            name: 'file_doc'
        },
        {
            name: 'date_sent'
        },
        {
            name: 'participant_id'
        }])
    });
    
    var rstore = new Ext.data.Store({
        remoteSort: true,
        sortInfo: {
            field: 'last_name',
            direction: 'ASC'
        },
        proxy: new Ext.data.HttpProxy({
            url: 'reviewers'
        }),
        reader: new Ext.data.JsonReader({
            root: 'reviewers',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [{
            name: 'first_name'
        },
        {
            name: 'last_name'
        },
        {
            name: 'institution'
        },
        {
            name: 'email'
        },
        {
            name: 'total_papers'
        }])
    });
    var areaForm = new Ext.FormPanel({
        id: 'pnlArea',
        renderTo: 'area-form',
        frame: true,
        title: "Select area",
        labelAlign: 'right',
        height: 60,
        width: 400,
        waitMsgTarget: true,
        layout: 'form',
        items: [new Ext.form.ComboBox({
            fieldLabel: 'Area',
            id: 'area',
            hiddenName: 'area_id',
            store: a_store,
            valueField: 'id',
            displayField: 'name_en',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            emptyText: 'Select area...',
            selectOnFocus: true,
            forseSelection: true,
            editable: false,
            width: 190,
            onSelect: function(record) {
                loadPapers(record.id);
                area_id = record.id;
                this.setValue(record.data[this.valueField || this.displayField]);
                this.collapse();
            }
        })]
    });
    function renderDownload(value, p, r) {
        var str = '';
        var img_pdf = '<img src="../../images/pdf.png">&nbsp;';
        var img_doc = '<img src="../../images/doc.png">&nbsp;';
        var pdf = r.data['file_pdf'];
        var doc = r.data['file_doc'];
        if (pdf != '') {
            str += String.format('<a href="../paper/download/?id={0}&ft=pdf">{2}</a><a href="../paper/download/?id={0}&ft=pdf">{1}</a>', value, pdf, img_pdf);
        }
        if (doc != '') {
            str += String.format('<br/><a href="../paper/download/?id={0}&ft=doc">{2}</a><a href="../paper/download/?id={0}&ft=doc">{1}</a>', value, doc, img_doc);
        }
        return str;
    }
    var upagingBar = new Ext.PagingToolbar({
        pageSize: 25,
        store: ustore,
        displayInfo: true,
        displayMsg: 'Displaying papers {0} - {1} of {2}',
        emptyMsg: "No papers to display"
    }); // create the grid
    var grid = new Ext.grid.GridPanel({
        store: ustore,
        columns: [{
            header: "Title",
            width: 150,
            dataIndex: 'title',
            sortable: true
        },
        {
            header: "Authors",
            width: 150,
            dataIndex: 'authors',
            sortable: true
        },
        {
            header: "Category",
            width: 100,
            dataIndex: 'category_name',
            sortable: true
        },        
        {
            header: "Date sent",
            width: 150,
            dataIndex: 'date_sent',
            sortable: true
        },
        {
            header: "Files",
            width: 100,
            dataIndex: 'id',
            sortable: true,
            renderer: renderDownload
        }],
        renderTo: 'unassigned-grid',
        width: 650,
        height: 540,
        title: 'Unassigned papers',
        frame: true,
        loadMask: true,
      //  bbar: upagingBar,
        viewConfig: {
            forceFit: true
        }
    });
    
    var rpagingBar = new Ext.PagingToolbar({
        pageSize: 100,
        store: rstore,
        displayInfo: true,
        displayMsg: 'Displaying reviewers {0} - {1} of {2}',
        emptyMsg: "No reviewers to display"
    });
    var assignAction = function() {
        var reviewers = rgrid.getSelectionModel().getSelections();
        var papers = grid.getSelectionModel().getSelections();
        var r_list = '';
        var rcount = reviewers.length;
        if (rcount <= 0) {
            Ext.Msg.alert('Information', 'Please select reviewers');
            return;
        }
        for (var i = 0; i < rcount; i++) {
            if (i < rcount - 1) {
                r_list += reviewers[i].id + ':';
            } else {
                r_list += reviewers[i].id;
            }
        }
        var p_list = '';
        var pcount = papers.length;
        if (pcount <= 0) {
            Ext.Msg.alert('Information', 'Please select papers to assign');
            return;
        }
        for (var i = 0; i < pcount; i++) {
            if (i < pcount - 1) {
                p_list += papers[i].id + ':';
            } else {
                p_list += papers[i].id;
            }
        }
        Ext.Ajax.request({
            url: 'assign',
            success: assignSuccess,
            failure: assignFail,
            params: {
                rList: r_list,
                pList: p_list
            }
        });
    }; // create the grid */
    
    
    var rgrid = new Ext.grid.GridPanel({
        store: rstore,
        columns: [{
            header: "Last Name",
            width: 100,
            dataIndex: 'last_name',
            sortable: true
        },
        {
            header: "First Name",
            width: 100,
            dataIndex: 'first_name',
            sortable: true
        },
        {
            header: "Institution",
            width: 100,
            dataIndex: 'institution',
            sortable: true
        },
        {
            header: "Email",
            width: 150,
            dataIndex: 'email',
            sortable: true
        },
        {
            header: "Total assigned",
            width: 50,
            dataIndex: 'total_papers',
            sortable: true
        }],
        renderTo: 'reviewers-grid',
        width: 500,
        height: 640,
        title: 'Reviewers',
        frame: true,
        loadMask: true,
        bbar: rpagingBar,
        waitMsgTarget: true,
        viewConfig: {
            forceFit: true
        },
        tbar: [{
            text: 'Assign',
            handler: assignAction,
            waitMsg: 'Assigning papers...',
            tooltip: 'Select papers and click to assign to selected reviewers'
        }]
    });
    var assignSuccess = function() {
        Ext.Msg.alert('Information', 'Papers assigned successfully');        
        loadPapers(area_id);
        rstore.load({
            params: {
                start: 0,
                limit: 100
            }
        });
    };
    var assignFail = function() {}; //var btn = new Ext.Button({name: 'btnAssign', text: 'Assign', handler: assignAction, renderTo: 'assign-btn'});					
    
    
    var loaded = function(r, options, success) {
        if (r) {
            area_id = r[0].id;
            loadPapers(area_id);            
            Ext.getCmp('area').setValue(r[0].id);
        }
    };
    a_store.load({
        callback: loaded
    });
    function loadPapers(area_id) {
        ustore.load({
            params: {
                start: 0,
                limit: 25,
                area_id: area_id
            }
        });    
    }
    rstore.load({
        params: {
            start: 0,
            limit: 100
        }
    });
});